import { Panel } from 'comps/common';
import { Form, Spin, Select, Input, Col, Row, Button, Modal } from 'antd';
import * as React from 'react';
const FormItem = Form.Item;
const Option = Select.Option;

class NewMachineForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      submiting: false,
      createState: {}
    };
  }

  doSubmit(evt) {
    evt.preventDefault();
    const { validateFields } = this.props.form;
    validateFields((error, values) => {
      if (!!error) {
        return;
      }
      this.setState({ submiting: true });
      return this.props.onSubmit(values, this.props.companyId)
        .then(() => {
          this.setState({ submiting: false });
          Modal.success({
            title: '添加机器成功',
            content: '正在执行一系列初始化安装，这需要花费一些时间，请稍后在机器列表查看安装结果',
            onOk: () => {
              this.props.onSuccess();
            }
          });
        })
        .catch((submitError) => {
          this.setState({ submiting: false });
          Modal.error({
            title: '添加机器失败',
            content: `添加机器时发生错误：${submitError.message}`
          });
        });
    });
  }

  render() {
    const { form: { getFieldProps }, isFetching = false, machineSources = [] } = this.props;

    const layer = {
      labelCol: {
        span: 8
      },
      wrapperCol: {
        span: 10
      }
    };

    const sourceIdField = getFieldProps('sourceId', {
      rules: [
        { type: 'integer', required: true, message: '请选择一个机器来源' }
      ]
    });
    const ipField = getFieldProps('ip', {
      rules: [
        { required: true, message: '请填写机器 IP' }
      ]
    });
    const portField = getFieldProps('port', {
      initialValue: 22
    });
    const userField = getFieldProps('user', {
      rules: [
        { required: true, message: '请填写有 root 权限的用户' }
      ]
    });
    const passwordField = getFieldProps('password', {
      rules: [
        { required: true, message: '请填写用户对应的密码' }
      ]
    });
    const adminField = getFieldProps('admin', {});

    const sourceOptions = [];
    machineSources.forEach(({ id, name, status }) => {
      if (status === 'ACTIVE') {
        sourceOptions.push(<Option key={id} value={id}>{name}</Option>);
      }
    })

    return (
      <Spin spinning={isFetching}>
        <Form horizontal onSubmit={::this.doSubmit} form={this.props.form}>
          <FormItem label='机器来源：' required {...layer}>
            <Select {...sourceIdField} style={{ width: '200px' }}>
              {sourceOptions}
            </Select>
          </FormItem>
          <FormItem label='机器 IP / 端口：' required {...layer} className='parent-item'>
            <Col span='16'>
              <FormItem>
                <Input {...ipField} placeholder='请输入机器内网 IP'/>
              </FormItem>
            </Col>
            <Col span='2'>
              <p className='ant-form-split'>/</p>
            </Col>
            <Col span='6'>
              <FormItem>
                <Input {...portField} placeholder='SSH 端口号'/>
              </FormItem>
            </Col>
          </FormItem>
          <FormItem label='用户名 / 密码：' required {...layer} className='parent-item'>
            <Col span='10'>
              <FormItem>
                <Input {...userField} placeholder='有 root 权限的用户'/>
              </FormItem>
            </Col>
            <Col span='2'>
              <p className='ant-form-split'>/</p>
            </Col>
            <Col span='12'>
              <FormItem>
                <Input type='password' {...passwordField} placeholder='和对应的密码'/>
              </FormItem>
            </Col>
          </FormItem>
          <FormItem label='管理员用户：' {...layer}>
            <Input {...adminField} placeholder='请输入平台使用的管理员用户'/>
          </FormItem>
          <Row>
            <Col span='16' offset='8'>
              <Button htmlType='submit' type='primary' loading={this.state.submiting}>添加</Button>
            </Col>
          </Row>
        </Form>
      </Spin>
    );
  }
}
NewMachineForm = Form.create()(NewMachineForm);

const NewMachine = ({ machineSourceFetching, machineSources, createMachine, closeSelf, companyId }) => {
  return (
    <Panel>
      <NewMachineForm isFetching={machineSourceFetching} machineSources={machineSources} onSubmit={createMachine}
        onSuccess={closeSelf} companyId={companyId}
      />
    </Panel>
  );
};

export default NewMachine;
